package org.millioncall.yueyoga.admin.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.millioncall.openplatform.common.PaginatedList;
import org.millioncall.openplatform.common.SpringApplicationContextHolder;
import org.millioncall.yueyoga.admin.dao.ResourceDAO;
import org.millioncall.yueyoga.admin.model.Resource;
import org.millioncall.yueyoga.admin.service.ResourceService;
import org.millioncall.yueyoga.common.security.ZhuwSecurityMetadataSource;
import org.springframework.stereotype.Service;
@Service
public class ResourceServiceImpl implements ResourceService {

	private ResourceDAO resourceDAO;

	@Override
	public boolean updateResource(Resource resource) {
		if (resource != null) {
			if (resource.getId() != null) {
				return resourceDAO.updateResource(resource) > 0;
			} else {
				ZhuwSecurityMetadataSource zsms  =   SpringApplicationContextHolder.getBean("zhuwSecurityMetadataSource");
				zsms.loadResourceDefine();
				return resourceDAO.saveResource(resource) > 0;
			}
		}
		return false;
	}

	@Override
	public boolean deleteResources(String ids) {
		ZhuwSecurityMetadataSource zsms  =   SpringApplicationContextHolder.getBean("zhuwSecurityMetadataSource");
		zsms.loadResourceDefine();
		List<Integer> rIds = new ArrayList<Integer>();
		if (StringUtils.isNotBlank(ids)) {
			String[] resourceIds = ids.split(",");
			if (resourceIds != null && resourceIds.length > 0) {
				for (String str : resourceIds) {
					rIds.add(Integer.valueOf(str));
				}
			}
			return resourceDAO.deleteResources(rIds) > 0;
		}
		return false;
	}

	@Override
	public PaginatedList<Resource> findAllResources(int start, int limit,
			Map<String, String> map) {
		return resourceDAO.findAllResources(start, limit, map);
	}

	public ResourceDAO getResourceDAO() {
		return resourceDAO;
	}

	public void setResourceDAO(ResourceDAO resourceDAO) {
		this.resourceDAO = resourceDAO;
	}

	@Override
	public List<Resource> findAuthorityResources(int auId) {
		return resourceDAO.findResourceByAuthorityId(auId);
	}

	@Override
	public List<Resource> findResources(boolean b) {
		return resourceDAO.findResources(true);
	}

	@Override
	public Resource findResourceByName(String name) {
		return this.resourceDAO.findResourceByName(name);
	}
}
